package concurrent;

/**
 * @File Info: leetcode -- <PrintIdInTurn>
 * @Author: 18362
 * @Create: 2022-03-14 13:14:56 星期一
 */

import java.util.concurrent.locks.LockSupport;

/**
 * 三个线程轮流打印ID，各自打印10次
 */
public class PrintIdInTurn {

    public static Object monitor = new Object();
    public static volatile int flag = 0;

    static class MyThread extends Thread {

        private int k;

        public MyThread(String name, int k) {
            super(name);
            this.k = k;
        }

        public void run() {
            long id = getId();
            synchronized (monitor) {
                try {
                    for (int i = 0; i < 10; i++) {
                        while (flag % 3 != k)
                            monitor.wait();
                        System.out.println(getName() + ": " + getId());
                        flag++;
                        monitor.notifyAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        new MyThread("thread-1", 0).start();
        new MyThread("thread-2", 1).start();
        new MyThread("thread-3", 2).start();
    }
}
